import org.jsecurity.authc.AuthenticationException
import org.jsecurity.authc.UsernamePasswordToken
import org.jsecurity.SecurityUtils
import grails.converters.JSON

class AuthController {
    def jsecSecurityManager
    def securityService

    def index = { redirect(action: 'login', params: params) }

    def login = {
        def school = checkDomain()
        if(!school){
            flash.message = "没有此学校，请检查你输入的域名是否正确！"
            return render(view: "../errors/siteStop")
        }else{
            if(!school.enable){
                flash.message = "此学校的被管理员停用，不能登录！"
                return render(view: "../errors/siteStop")
           }

            if(new Date() > school.end){
                log.info("有效时间已过")
                flash.message = "此学校的有效时间已过，不能登录！"
                return render(view: "../errors/siteStop")
           }
        }
        return [ username: params.username,schoolId:school.id,rememberMe: (params.rememberMe != null), targetUri: params.targetUri ]
    }

    private School checkDomain(){
           // 根据子域名判断学校
        def subDomain = org.apache.commons.lang.StringUtils.substringBefore(request.getServerName() ,".")
        log.info("login.authBefore subDomain = ${subDomain}")
 
        if(subDomain){
           return School.findBySubDomain(subDomain) 
        } 
    }

    def signIn = {
        Author.findByUsernameAndSchoolId(params.username,params.schoolId.toLong()){
            flash.message = message(code: "login.failed")
            return redirect(action: 'login')
        }
        def authToken = new UsernamePasswordToken(params.username, params.password)

        // Support for "remember me"
        if (params.rememberMe) {
            authToken.rememberMe = true
        }

        try{
            // Perform the actual login. An AuthenticationException
            // will be thrown if the username is unrecognised or the
            // password is incorrect.
            this.jsecSecurityManager.login(authToken)
            if(SecurityUtils.subject.hasRole("SUPER_ADMIN")){
                return redirect(controller:"site",action:"list")
            }
            def author = Author.findByUsername(params.username)
            // If a controller redirected to this page, redirect back
            // to it. Otherwise redirect to the root URI.
//            def targetUri = params.targetUri ?: "/home/blog/${author.id}"
            def targetUri = "/home/blog/${author.id}"

            log.info "Redirecting to '${targetUri}'."
            //session.loginID = author.id
            redirect(uri: targetUri)
        }
        catch (AuthenticationException ex){
            // Authentication failed, so display the appropriate message
            // on the login page.
            log.info "Authentication failure for user '${params.username}'."
            flash.message = message(code: "login.failed")

            // Keep the username and "remember me" setting so that the
            // user doesn't have to enter them again.
            def m = [ username: params.username ]
            if (params.rememberMe) {
                m['rememberMe'] = true
            }

            // Remember the target URI too.
            if (params.targetUri) {
                m['targetUri'] = params.targetUri
            }

            // Now redirect back to the login page.
            
            redirect(action: 'login', params: m)
        }
    }

    def signInAjax = {
        def author = Author.findByUsername(params.username)
        if(author && !author.enabled){
            return render(['success':false,'message' : '此用户已被管理员锁定！'] as JSON) 
        }

        def authToken = new UsernamePasswordToken(params.username, params.password)
        // Support for "remember me"
        if (params.rememberMe) {
            authToken.rememberMe = true
        }
        try{
            // Perform the actual login. An AuthenticationException
            // will be thrown if the username is unrecognised or the
            // password is incorrect.
            this.jsecSecurityManager.login(authToken)
            //def author = Author.findByUsername(params.username)
            // If a controller redirected to this page, redirect back
            // to it. Otherwise redirect to the root URI.
            session.loginID = author.id
//            redirect(uri: targetUri)
            return render(['success':true,'message' : "${author.id}"] as JSON) 
        }
        catch (AuthenticationException ex){
            // Authentication failed, so display the appropriate message
            // on the login page.
            log.info "Authentication failure for user '${params.username}'."
            flash.message = message(code: "login.failed")

            // Keep the username and "remember me" setting so that the
            // user doesn't have to enter them again.
            def m = [ username: params.username ]
            if (params.rememberMe) {
                m['rememberMe'] = true
            }
            // Now redirect back to the login page. 
            return render(['success':false,'message' : '登录名或密码错误，请重新登录！'] as JSON) 
        }
    }

    def signOutAjax = {
        // Log the user out of the application.
        def currentUserId = securityService.getCurrentUser().id
        SecurityUtils.subject?.logout()

        // For now, redirect back to the home page.
        return render(['success':true,'message' : "${currentUserId}"] as JSON) 
    }

    def signOut = {
        // Log the user out of the application.
        SecurityUtils.subject?.logout()

        // For now, redirect back to the home page.
        redirect(uri: '/')
    }

    def unauthorized = {
        render 'You do not have permission to access this page.'
    }

   
}
